var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var validate = require('../common/validate.js');
var permission = require('../common/permission.js');
var fs = require('fs');

var multer = require('multer');
var storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, './file/admin')
    },
    filename: function(req, file, cb) {
        cb(null, file.originalname)
    }
});
var upload = multer({
    storage: storage
});

router.get('/', permission.checkLogin, admin);
router.post('/work/allwork', allwork);

router.post('/work/mas', permission.checkLogin, getMaster);
router.post('/work/updateself', permission.checkLogin, permission.isHighPosition, updateSelf);

router.post('/work/workDetail', permission.checkLogin, permission.isLowPosition, workDetail);
router.post('/work/editWork', permission.checkLogin, permission.isLowPosition, editWorkMiddle, editWork);
router.post('/work/newWork', permission.checkLogin, permission.isLowPosition, newWork);
router.post('/work/masCheck', permission.checkLogin, permission.isLowPosition, masCheck);
router.post('/work/masDownload', permission.checkLogin, permission.isLowPosition, masDownload);
router.post('/work/homeworkFile', upload.any(), homeworkFile); // 上传作业接口

router.post('/grade/homeworkscore', permission.checkLogin, permission.isHighPosition, homeworkScore);

function admin(req, res, next) {
    res.render('admin', {
        title: 'EUX后台管理中心',
        user: req.session.user
    });
}

// 获取所有作业
function allwork(req, res, next) {
    // var userid      = req.body.userid;
    var userid = req.session.user.userid;
    var position = req.session.user.position;
    var department = req.session.user.department;

    var Homework = mongoose.model('Homework');

    Homework.find({
        department: department
    }, function(err, result) {
        if (err) throw err;
        if (position === 6) allworkStaff(res, result, userid);
        else allworkMaster(res, result);
    })
}

// 处理所有作业 员工
function allworkStaff(res, result, userid) {
    var toBeGet = ['setDate', 'homeworkName', 'deadLine', 'homeworkDetail', 'display', 'file'];
    var toBeGetUser = ['selfCheck', 'masterCheck', 'commentID', 'comment', 'workLink', 'workName'];
    var workArr = [];

    result.forEach(function(resultOne) {
        var workObj = {};
        workObj.user = {};
        toBeGet.forEach(function(item) {
            workObj[item] = resultOne[item];
        })
        toBeGetUser.forEach(function(item) {
            workObj.user[item] = resultOne[userid][item];
        })
        workArr.push(workObj);
    })

    // console.log(workArr);
    res.send(JSON.stringify(workArr));
}

//处理所有作业 主管
function allworkMaster(res, result) {
    var toBeGet = ['setDate', 'homeworkName', 'deadLine', 'inCharge', 'staffNum', 'updateNum'];
    var workArr = [];

    result.forEach(function(resultOne) {
            var workObj = {};
            toBeGet.forEach(function(item) {
                workObj[item] = resultOne[item];
            })
            workArr.push(workObj);
        })
        // console.log(workArr);
    res.send(JSON.stringify(workArr));
}

function getMaster(req, res, next) {

    var masterID = req.body.commentID;

    var User = mongoose.model('User');
    User.findOne({
        userid: masterID
    }, function(err, result) {
        if (err) throw err;
        var obj = {
            username: result.username,
            avatar: result.avatar
        }
        res.send(JSON.stringify(obj));
    })
}

// 更新自我评价
function updateSelf(req, res, next) {

    var userid = req.session.user.userid;
    var homeworkName = req.body.homeworkName;
    var selfCheck = req.body.selfCheck;
    var User = mongoose.model('User');
    var Homework = mongoose.model('Homework');
    User.findOne({
        userid: userid
    }, function(err, result) {
        if (err) throw err;
        if (!result) {
            return res.send('fail');
        } else {
            Homework.findOne({
                homeworkName: homeworkName
            }, function(err, result) {
                if (err) throw err;
                if (!result) {
                    return res.send('fail');
                } else {
                    result[userid].selfCheck = selfCheck;
                    result.save(function(err) {
                        if (err) throw err;
                        console.log("success!")
                        return res.send('success');
                    })
                }
            })
        }
    })
}

// 主管所有作业页面 查看详情
function workDetail(req, res, next) {
    var homeworkName = req.body.homeworkName;
    var Homework = mongoose.model('Homework');
    Homework.findOne({
        homeworkName: homeworkName,
        department: req.session.user.department
    }, function(err, result) {
        if (err) throw err;
        if (!result) return res.send("fail");

        var detailObj = {};
        detailObj.homeworkDetail = result.homeworkDetail;
        detailObj.file = result.file;
        for (item in result) {
            if (typeof result[item] === 'object' && result[item].workLink) {
                // detailObj[item] = {
                //     isNew       : result[item].isNew,
                //     workLink    : result[item].workLink,
                //     workName    : result[item].workName
                // }
                detailObj[item] = result[item];
                // if(result[item].isNew){
                //     result[item].isNew = false;
                // }
            }
        }
        result.save(function(err) {
                if (err) throw err;
            })
            // console.log(detailObj)
        res.send(JSON.stringify(detailObj))
    })
}

// 修改作业 中间件
function editWorkMiddle(req, res, next) {

    var oldName = req.body.oldName;
    var homeworkName = req.body.homeworkName;
    var Homework = mongoose.model('Homework');

    if (validate.emptystring(homeworkName)) {
        return res.send("Empty")
    }

    // 作业修改-未改名
    if (oldName === homeworkName) next();
    else {
        Homework.findOne({
            homeworkName: homeworkName
        }, function(err, result) {
            if (err) throw err;
            if (result) {
                return res.send("SameName")
            } else {
                next();
            }
        })
    }


}

// 修改作业
function editWork(req, res, next) {
    var oldName = req.body.oldName;
    var homeworkName = req.body.homeworkName;
    var homeworkDetail = req.body.homeworkDetail;
    var file = req.body.file;
    var Homework = mongoose.model('Homework');


    Homework.findOne({
        homeworkName: oldName,
        department: req.session.user.department
    }, function(err, result) {
        if (err) throw err;
        if (!result) {
            return res.send('NotFound');
        } else {
            result.homeworkName = homeworkName;
            result.homeworkDetail = homeworkDetail;
            result.file = file;
            result.save(function(err) {
                if (err) throw err;
                return res.send('success')
            })
        }
    })
}

// 新建作业
function newWork(req, res, next) {
    var homeworkName = req.body.homeworkName;
    var homeworkDetail = req.body.homeworkDetail;
    var deadLine = req.body.deadLine;
    var file = req.body.file;
    var Homework = mongoose.model('Homework');
    var User = mongoose.model('User');

    if (validate.emptystring(homeworkName)) {
        return res.send("Empty")
    }

    Homework.findOne({
        homeworkName: homeworkName
    }, function(err, result) {
        if (err) throw err;
        if (result) return res.send("SameName");
        else {
            User.find({
                department: req.session.user.department,
                position: 6,
                validated: true
            }, function(err, result) {
                if (err) throw err;
                var newWorkObj = {
                    homeworkName: homeworkName,
                    homeworkDetail: homeworkDetail,
                    deadLine: deadLine,
                    file: file,
                    department: req.session.user.department,
                    inCharge: req.session.user.username,
                    staffNum: result.length
                }
                result.forEach(function(item) {
                    newWorkObj[item.userid] = {
                        isStaff: 　true
                    };
                })
                var toBeSet = new Homework(newWorkObj);
                toBeSet.save(function(err) {
                    if (err) throw err;
                    res.send("success");
                })
            })
        }
    })
}

// 主管打分
function masCheck(req, res, next) {
    var homeworkName = req.body.homeworkName;
    var masterCheck = req.body.masterCheck;
    var userid = req.body.userid;
    var comment = req.body.comment;
    var commentID = req.session.user.userid;
    var Homework = mongoose.model('Homework');

    Homework.findOne({
        homeworkName: homeworkName,
        department: req.session.user.department
    }, function(err, result) {
        if (err) throw err;
        if (!result) return res.send("NotFound");
        else if (!result[userid]) {
            return res.send("NotFoundPerson");
        } else {
            result[userid].masterCheck = masterCheck;
            result[userid].comment = comment;
            result[userid].commentID = commentID;
            result[userid].isNew = false;
            result.save(function(err) {
                if (err) throw err;
                res.send('success');
            })
        }
    })
}

function masDownload(req, res, next) {
    var homeworkName = req.body.homeworkName;
    var staffArr = req.body.staffArr;
    var linkArr = [];
    var Homework = mongoose.model('Homework');

    Homework.findOne({
        homeworkName: homeworkName,
        department: req.session.user.department
    }, function(err, result) {
        if (err) throw err;
        if (!result) return res.send("NotFound");
        else {
            staffArr.forEach(function(item) {
                if (result[item] && result[item].workLink) {
                    linkArr.push(result[item].workLink);
                }
            })
            return res.send(JSON.stringify(linkArr));
        }
    })

}

// 获取员工的作业绩效
function homeworkScore(req, res, next) {
    var user = req.session.user,
        userid = user.userid;
    var selfScore = 0,
        maxScore = 0,
        total = 0,
        rank = 0;
    var cacheArr = [],
        cacheObj = {};
    var Homework = mongoose.model('Homework');

    Homework.find({
        department: user.department
    }, function(err, homeworks) {
        if (err) {
            console.log(err);
            res.send(err);
        }
        var length = homeworks.length;
        for (var i = 0; i < length; i++) {
            var homework = homeworks[i];
            for (var key in homework) {

                // 需要过滤掉数据库和用户无关的属性
                if (typeof(homework[key]) == 'object' && homework[key].masterCheck) {

                    // 将匹配到的用户的评分加入缓存对象
                    var masCheck = parseFloat(homework[key].masterCheck);
                    if (cacheObj[key]) {
                        cacheObj[key] += masCheck;
                    } else {
                        cacheObj[key] = masCheck;
                    }
                }
            }
        };


        // 存入缓存数组
        for (var item in cacheObj) {
            if (cacheObj.hasOwnProperty(item)) {
                cacheArr.push({
                    'name': item,
                    'score': cacheObj[item]
                })
            }
        }

        // 排序之后找到最大分数和总数
        for (var m = 0; m < cacheArr.length; m++) {
            for (var n = 0; n < cacheArr.length; n++) {
                if (cacheArr[n].score > cacheArr[m].score) {
                    var swap = cacheArr[n];
                    cacheArr[n] = cacheArr[m];
                    cacheArr[m] = cacheArr[n];
                }
            }
        }

        maxScore = cacheArr[0].score;
        for (var i = 0; i < cacheArr.length; i++) {
            if (cacheArr[i].name == userid) {
                selfScore = cacheArr[i].score;
                rank = i + 1;
            }
        }
        total = cacheArr.length;

        res.send({
            'maxScore': maxScore,
            'selfScore': selfScore,
            'total': total,
            'rank': rank
        });
    });

}

// 上传作业
function homeworkFile(req, res, next) {
    var user = req.session.user;
    var Homework = mongoose.model('Homework');

    if (user.position == 6) {
        staffHomeworkFile();
    } else {
        masterHomeworkFile();
    }

    function staffHomeworkFile() {
        var userid = user.userid;
        var workLink = req.body.workLink;
        var homeworkName = req.body.homeworkName;

        Homework.findOne({
            'homeworkName': homeworkName
        }, function(err, result) {
            if (err) {
                console.log(err);
                res.send(err);
            }
            if (workLink !== 'undefined') {
                // 已经提交则删除原有文件
                fs.unlink('./file/admin/' + result[userid]['workName'], function(err) {
                    if (err) {
                        console.log(err);
                    }
                });
            }
            // 添加新文件路径和名称,
            // 下载路径不能包含中文，所以进行一次编码，文件下载路由再进行解码
            result[userid]['workLink'] = '/file/admin/' + encodeURI(req.files[0].filename);
            result[userid]['workName'] = req.files[0].originalname;
            result[userid]['isNew'] = true;
            result.save(function (err) {
                if (err) {
                    console.log(err)
                }
                res.send('success');
            })
        })
    }

    function masterHomeworkFile() {
        var homeworkName = req.body.homeworkName;

        Homework.findOne({
            'homeworkName': homeworkName
        }, function(err, result) {
            if (err) {
                console.log(err);
            }
            console.log(result);
            // 已有则删除原文件
            if (result.file) {
                fs.unlink('./file/admin/' + decodeURI(result.file.split('/')[3]), function(err) {
                    if (err) {
                        console.log(err);
                    }
                });
            }
            result['file'] = '/file/admin/' + encodeURI(req.files[0].filename);

            result.save(function (err) {
                if (err) {
                    console.log(err);
                }
                res.send('success');
            })
        });
    }
}

module.exports = router;
